﻿using HouseResource.Forms;
using HouseResourceAnalysis.Models;
using HouseResourceAnalysis.Target;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HouseResource
{
    public partial class HouseTable : Form
    {
        public DataTable dtResult = new DataTable();
        private Task GetDataTask = null;

        public HouseTable()
        {
            InitializeComponent();

            dtResult.Columns.Add("楼盘名称");
            dtResult.Columns.Add("状态");
            dtResult.Columns.Add("单价(元/m²)");
            dtResult.Columns.Add("开发商");
            dtResult.Columns.Add("物业");
            dtResult.Columns.Add("楼盘链接");
            dtResult.Columns.Add("开发商前列");
            dtResult.Columns.Add("物业前列");
            dtResult.Columns.Add("开发商物业是一家");
            dtResult.Columns.Add("得分");
            InitGrid();
            BaseResource.InitRanking();
        }

        private void Bind()
        {
            dtResult.Rows.Clear();

            gridHouse.BeginInvoke((MethodInvoker)delegate ()
            {
                gridHouse.Rows.Clear();
            });
            txtLog.BeginInvoke((MethodInvoker)delegate ()
            {
                txtLog.Text = string.Empty;
            });

            SetLog("开始获取楼盘总数....");

            var url = GetUrl();
            AnJuKe house = new AnJuKe() { Url = url };
            var detailLinks = GetLinks(url);

            SetLog($"详情页链接初始化成功，楼盘数：{detailLinks.Count}");

            foreach (var item in detailLinks)
            {
                var model = house.GetHouse(item);
                model.Status = model.Status ?? string.Empty;
                if (model.Status.Contains("售罄") || model.Status.Contains("待售"))
                {
                    SetLog($" {model.Name} 状态为{model.Status},已智能过滤。");
                    continue;
                }
                var dr = dtResult.NewRow();
                dr["楼盘名称"] = model.Name;
                dr["状态"] = model.Status;
                dr["单价(元/m²)"] = model.UnitPrice;
                dr["开发商"] = model.DevelopersCorp;
                dr["物业"] = model.PropertyCorp;
                dr["楼盘链接"] = model.DetailLink;
                dr["开发商前列"] = model.IsTop_DevelopersCorp ? "是" : "否";
                dr["物业前列"] = model.IsTop_PropertyCorp ? "是" : "否";
                dr["开发商物业是一家"] = model.IsDevelopersEqualProperty ? "是" : "否";
                dr["得分"] = model.Score;
                //dtResult.Rows.InsertAt(dr, 0);

                gridHouse.BeginInvoke((MethodInvoker)delegate ()
                {
                    gridHouse.Rows.Insert(0, dr.ItemArray);
                });

                SetLog($" {model.Name} 获取成功。");

                Thread.Sleep(200);
            }
        }

        private void btnExp_Click(object sender, EventArgs e)
        {
            if (gridHouse.Rows.Count <= 0)
            {
                MessageBox.Show("请先搜索数据！");
                return;
            }

            ExcelHelper.ExportExcel("房源分析结果", gridHouse);
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            GetDataTask = new Task(() =>
            {
                Bind();
                SetLog($"分析完成，共有{gridHouse.Rows.Count}条有效数据！");
                MessageBox.Show($"分析完成，共有{gridHouse.Rows.Count}条有效数据！");
                return;
            });
            GetDataTask.Start();
        }

        private void btnSuspend_Click(object sender, EventArgs e)
        {
        }

        private List<string> GetLinks(string url)
        {
            AnJuKe house = new AnJuKe() { Url = url };
            return house.GetDetailLinks();
        }

        private string GetRaidoButtonValue(GroupBox groupBox)
        {
            if (groupBox.Controls.Count <= 0)
            {
                return string.Empty;
            }
            foreach (var item in groupBox.Controls)
            {
                var radioButton = (item as RadioButton);
                if (radioButton.Checked)
                {
                    return radioButton.Name;
                }
            }
            return string.Empty;
        }

        private string GetUrl()
        {
            string url = "http://cs.fang.anjuke.com/loupan/all/w1_";
            var unitPrice = GetRaidoButtonValue(this.group_UnitPrice);
            var houseLayout = GetRaidoButtonValue(this.group_HouseLayout);
            unitPrice = unitPrice.Equals("PriceAll") ? string.Empty : unitPrice;
            houseLayout = houseLayout.Equals("LayoutAll") ? string.Empty : houseLayout;
            if (!string.IsNullOrWhiteSpace(unitPrice))
            {
                url += unitPrice + "_";
            }
            if (!string.IsNullOrWhiteSpace(houseLayout))
            {
                url += houseLayout + "_";
            }

            return url.TrimEnd('_');
        }

        private void InitGrid()
        {
            foreach (DataColumn item in dtResult.Columns)
            {
                var column = new DataGridViewTextBoxColumn();
                column.HeaderText = item.ColumnName;
                gridHouse.Columns.Add(column);
            }
        }

        private void menu_DevelopersManager_Click(object sender, EventArgs e)
        {
            new FileManager("全国开发商排行榜设置", BaseResource.DevelopersCorpRankingFile).Show();
        }

        private void menu_FilterKeywordsManager_Click(object sender, EventArgs e)
        {
            new FileManager("分词过滤关键字", BaseResource.FilterKeywordsFile).Show();
        }

        private void menu_PropertyManager_Click(object sender, EventArgs e)
        {
            new FileManager("全国物业公司排行榜设置", BaseResource.PropertyCorpRankingFile).Show();
        }

        private void menuItem_Terms_Click(object sender, EventArgs e)
        {
        }

        private void menuItem_TermsSet_Click(object sender, EventArgs e)
        {
            new FileManager("分词设置", BaseResource.TermsFile).Show();
        }

        private void menuItem_TermsStudy_Click(object sender, EventArgs e)
        {
            new TermsManager().Show();
        }

        private void SetLog(string msg)
        {
            txtLog.BeginInvoke((MethodInvoker)delegate ()
            {
                txtLog.Text = $"{msg}{Environment.NewLine}" + txtLog.Text;
            });
        }
    }
}